import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:rabbit_mobile/i18n/strings.g.dart';
import 'package:rabbit_mobile/utils/common_utils.dart';
import 'package:rabbit_mobile/service/home.api.dart';
import '../../provide/riverpod_provider.dart';

class Login extends ConsumerStatefulWidget {
  const Login({super.key});

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends ConsumerState<Login> {
  /// 賬號的controller
  late TextEditingController? _accountController;

  /// 密碼的controller
  late TextEditingController? _passwordController;

  /// 輸入框焦點控制器
  late FocusNode? _accountFocusNode;

  /// 密碼輸入框控制器
  late FocusNode? _passwordFocusNode;

  /// 是否同意條款
  bool isAgree = false;

  /// 密碼是否可見
  bool obscureTextToggle = true;

  /// 監聽賬號輸入框是否有值
  bool accountIsValue = false;

  /// 監聽密碼輸入框書否有值
  bool passwordIsValue = false;

  @override
  void initState() {
    super.initState();
    _accountController = TextEditingController();
    _passwordController = TextEditingController();
    _accountFocusNode = FocusNode();
    _passwordFocusNode = FocusNode();
    _accountController!.addListener(() {
      setState(() {
        accountIsValue = _accountController!.text.isNotEmpty;
      });
    });
    _passwordController!.addListener(() {
      setState(() {
        passwordIsValue = _passwordController!.text.isNotEmpty;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _accountController?.dispose();
    _passwordController?.dispose();
    _accountFocusNode?.dispose();
    _passwordFocusNode?.dispose();
  }

  /// 登錄時間處理函數
  void _handleLogin() async {
    // 校驗用戶登錄信息
    // 校驗賬號密碼是否爲空
    if (_accountController!.text.isEmpty || _passwordController!.text.isEmpty) return;
    // 賬號正則匹配
    RegExp accountOrPasswordRegExp = RegExp(r'^[0-9a-zA-Z]{5,20}$');
    bool isMatchAccount = accountOrPasswordRegExp.hasMatch(_accountController!.text);
    bool isMatchPassword = accountOrPasswordRegExp.hasMatch(_passwordController!.text);
    if (!isMatchAccount || !isMatchPassword) {
      EasyLoading.showError('格式錯誤');
      return;
    }
    if (!isAgree) {
      EasyLoading.showError('請點擊方框同意條款');
      return;
    }
    final data = {
      "account": _accountController!.text,
      "password": _passwordController!.text,
    };
    try {
      final login_data = await LoginApi.loginFetch(data);
      await userInfoSettingCache(login_data);
      ref.refresh(getShoppingProvider);
      Beamer.of(context).beamBack();
    } catch (e) {
      print(e);
    }
  }

  /// page background
  Widget _backgroundBuildWidget() {
    return Column(
      children: [
        Container(
          width: double.infinity,
          height: 160,
          decoration: const BoxDecoration(color: Color(0xFF00CEA8)),
        ),
        Container(
          width: double.infinity,
          height: MediaQuery.of(context).size.height - 160,
          decoration: const BoxDecoration(color: Color(0xFFFEF7FF)),
        ),
      ],
    );
  }

  /// account and password widget
  Widget _loginBuildWidget() {
    return Positioned(
      top: 140,
      left: 0,
      right: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Container(
          width: double.infinity,
          height: 200,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(
              Radius.circular(10),
            ),
          ),
          child: Padding(
            padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Container(
                  decoration: const BoxDecoration(
                    border: Border(
                      bottom: BorderSide(color: Color.fromARGB(67, 158, 158, 158), width: 1),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        t.account,
                        style: const TextStyle(color: Colors.black, fontSize: 16),
                      ),
                      Expanded(
                        flex: 1,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10),
                          child: TextField(
                            focusNode: _accountFocusNode,
                            controller: _accountController,
                            decoration: const InputDecoration(
                                hintText: "請輸入用戶賬號或手機號",
                                border: InputBorder.none,
                                hintStyle: TextStyle(fontSize: 12, color: Color.fromARGB(189, 158, 158, 158))),
                            cursorColor: const Color(0xFF00CEA8),
                            style: const TextStyle(fontSize: 14, color: Color.fromARGB(161, 0, 0, 0)),
                            keyboardType: TextInputType.text,
                          ),
                        ),
                      ),
                      accountIsValue
                          ? GestureDetector(
                              onTap: () {
                                setState(() {
                                  _accountController?.clear();
                                });
                              },
                              child: const Icon(Icons.close, size: 20, color: Color.fromARGB(189, 158, 158, 158)),
                            )
                          : Container()
                    ],
                  ),
                ),
                Container(
                  decoration: const BoxDecoration(
                    border: Border(
                      bottom: BorderSide(color: Color.fromARGB(67, 158, 158, 158), width: 1),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        t.password,
                        style: const TextStyle(color: Colors.black, fontSize: 16),
                      ),
                      Expanded(
                        flex: 1,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10),
                          child: TextField(
                            focusNode: _passwordFocusNode,
                            controller: _passwordController,
                            decoration: const InputDecoration(
                                hintText: "6-20位數字、字母和符號組件",
                                border: InputBorder.none,
                                hintStyle: TextStyle(fontSize: 12, color: Color.fromARGB(189, 158, 158, 158))),
                            style: const TextStyle(fontSize: 14, color: Color.fromARGB(161, 0, 0, 0)),
                            cursorColor: const Color(0xFF00CEA8),
                            obscureText: obscureTextToggle,
                            keyboardType: TextInputType.number,
                          ),
                        ),
                      ),
                      passwordIsValue
                          ? GestureDetector(
                              onTap: () {
                                setState(() {
                                  _passwordController?.clear();
                                });
                              },
                              child: const Icon(Icons.close, size: 20, color: Color.fromARGB(189, 158, 158, 158)),
                            )
                          : Container(),
                      const SizedBox(
                        width: 10,
                      ),
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            obscureTextToggle = !obscureTextToggle;
                          });
                        },
                        child: obscureTextToggle
                            ? Image.asset(
                                'assets/yanjing_on.png',
                                width: 18,
                                height: 18,
                              )
                            : Image.asset(
                                'assets/yanjing.png',
                                width: 18,
                                height: 18,
                              ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// eyes image
  Widget _eyesImageWidget() {
    return Positioned(
      top: 30,
      left: 0,
      right: 0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: SizedBox(
          child: Column(
            children: [
              obscureTextToggle ? Image.asset('assets/close_eyes_half.png') : Image.asset('assets/open_eyes.png'),
            ],
          ),
        ),
      ),
    );
  }

  /// Terms widget
  Widget _agreeTermsWidget() {
    return Positioned(
      top: 380,
      right: 0,
      left: 0,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            GestureDetector(
              onTap: () {
                setState(() {
                  isAgree = !isAgree;
                });
              },
              child: Container(
                padding: const EdgeInsets.only(right: 20),
                child: isAgree ? Image.asset('assets/isAgree_on.png') : Image.asset('assets/isAgree.png'),
              ),
            ),
            SizedBox(
              width: 240,
              child: Text.rich(
                t.ternms.text(
                  privacyTerms: TextSpan(
                    text: t.privacyTerms,
                    style: const TextStyle(fontSize: 12, color: Color(0xFF00CEA8)),
                  ),
                  serviceTerms: TextSpan(
                    text: t.serviceTerms,
                    style: const TextStyle(fontSize: 12, color: Color(0xFF00CEA8)),
                  ),
                ),
                style: const TextStyle(fontSize: 12, color: Colors.grey),
                maxLines: 3,
              ),
            )
          ],
        ),
      ),
    );
  }

  /// LoginButton Widget
  Widget _loginButtonWidget() {
    return Positioned(
      top: 420,
      left: 0,
      right: 0,
      child: TextButton(
        style: ButtonStyle(
          overlayColor: WidgetStateProperty.all(Colors.transparent), // 移除水波纹效果
        ),
        onPressed: _handleLogin,
        child: Container(
          alignment: Alignment.center,
          width: double.infinity,
          height: 50,
          decoration:
              const BoxDecoration(color: Color(0xFF00CEA8), borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Text(
            t.login,
            style: const TextStyle(
              fontSize: 16,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }

  /// iphone number login and more help
  Widget _iphoneLoginMoreHelp() {
    return Positioned(
      top: 500,
      right: 0,
      left: 0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Text(
            t.code_login,
            style: const TextStyle(fontSize: 16, color: Colors.grey),
          ),
          Text(
            t.need_help,
            style: const TextStyle(fontSize: 16, color: Color(0xFF00CEA8)),
          ),
        ],
      ),
    );
  }

  /// more login
  Widget _moreLoginWidget() {
    return Positioned(
      top: 650,
      right: 0,
      left: 0,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 24),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Expanded(
                  child: Divider(
                    thickness: 1,
                    endIndent: 10,
                    color: Colors.grey,
                  ),
                ),
                Text(
                  t.more_login,
                  style: const TextStyle(fontSize: 16.0, color: Colors.grey),
                ),
                const SizedBox(width: 10),
                const Expanded(
                  child: Divider(
                    thickness: 1,
                    color: Colors.grey,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Image.asset('assets/icon_login_qq.png'),
              Image.asset('assets/icon_login_wechat.png'),
              Image.asset('assets/icon_login_weibo.png'),
            ],
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF00CEA8),
        leading: IconButton(
          onPressed: () {
            Beamer.of(context).beamBack();
          },
          icon: Image.asset('assets/fanhui_light.png'),
        ),
        actions: [
          GestureDetector(
            onTap: () {
              Beamer.of(context).beamToNamed('/register');
            },
            child: Container(
              padding: const EdgeInsets.only(right: 20),
              alignment: Alignment.center,
              child: Text(
                t.new_user_login_up,
                style: const TextStyle(
                  fontSize: 14,
                  color: Colors.white,
                ),
              ),
            ),
          )
        ],
      ),
      body: GestureDetector(
        onTap: () {
          _accountFocusNode?.unfocus();
          _passwordFocusNode?.unfocus();
        },
        child: SingleChildScrollView(
          // physics: const NeverScrollableScrollPhysics(),
          child: Column(
            children: [
              Stack(
                children: [
                  _backgroundBuildWidget(),
                  _loginBuildWidget(),
                  _eyesImageWidget(),
                  _agreeTermsWidget(),
                  _loginButtonWidget(),
                  _iphoneLoginMoreHelp(),
                  _moreLoginWidget(),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}
